/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package core;

import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Jorge
 */
public abstract class FileServerCallBack<Integer> implements IServerCallBack<Integer,byte[]>{

    private FileCallBack callback;

    private int key;

    private int size=0;

    private List<byte[]> tmp= new LinkedList<byte[]>();
    private int tmpSize=0;

    public FileServerCallBack(FileCallBack callback) {
        this.callback = callback;
    }
  

     public void onFinish() {
        callback.onResult();
    }

    public void onReadHeader(int operation, int numArgs, ProtocolSD protocolSD) {

    }

    public void onReadArgument(byte[] data, ProtocolSD protocolSD) {

    }

    public void onReadArgumentSize(int size, ProtocolSD protocolSD) {
        this.key = -1;
        this.tmpSize=0;
        this.size = size;
        tmp.clear();
    }

    public void onReadAllArguments(ProtocolSD protocolSD) {

    }

    public void onWriteComplete(ProtocolSD protocolSD) {

    }

    public void onFinishConnect() {

    }

    public void onReadParcialParam(byte[] readedBytes, int offset, int limit) {
        if(key==-1){
            if(readedBytes.length>=4-tmpSize){
                tmp.add(ProtocolSD.subArray(readedBytes, 0, 4-tmpSize));
                byte [] bsAux= ProtocolSD.joinBuffer(tmp, 4);
                key = ProtocolSD.byteArrayToInt(bsAux, 0);
                callback.onNewFile(key,size-4);
                if(4-tmpSize != readedBytes.length){
                    
                    callback.onReadParcialParam(ProtocolSD.subArray(readedBytes, 4-tmpSize, readedBytes.length), offset, limit-4+tmpSize);
                }
                if(offset+limit==size){
                    callback.onFinishReadFile();
                }
            }else{
                tmp.add(readedBytes);
                tmpSize+=readedBytes.length;
            }
        }else{
            
            callback.onReadParcialParam(readedBytes, offset-4, limit);
            if(offset+limit==size){
                callback.onFinishReadFile();
            }
        }
        
    }

    public void onNewResult(Integer key, byte[] v) {
        
    }

    public void onError(Exception e) {
        callback.onError(e);
    }


    


    

    

}
